package com.motu.vertx.module.utility.ClassReload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;

public class MyClassLoader extends ClassLoader { 
 
    private String basedir;
    private HashSet<String> dynaclazns;
 
    public MyClassLoader(String basedir, String[] clazns) { 
        super(null);
        this.basedir = basedir; 
        dynaclazns = new HashSet<String>(); 
        loadClassByMe(clazns);
    } 
 
    private void loadClassByMe(String[] clazns) { 
        for (int i = 0; i < clazns.length; i++) { 
            try {
				loadDirectly(clazns[i]);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
            dynaclazns.add(clazns[i]); 
        } 
    } 
 
    private Class<?> loadDirectly(String name) throws Exception {
        Class<?> cls = null; 
        StringBuffer sb = new StringBuffer(basedir); 
        String classname = name.replace('.', File.separatorChar) + ".class";
        sb.append(File.separator + classname); 
        File classF = new File(sb.toString());
        cls = instantiateClass(name,new FileInputStream(classF),
            classF.length()); 
        return cls; 
    }           
 
    private Class<?> instantiateClass(String name,InputStream fin,long len) throws IOException{ 
        byte[] raw = new byte[(int) len]; 
        fin.read(raw); 
        fin.close(); 
        return defineClass(name,raw,0,raw.length);
    } 
     
    
    @Override
    protected Class loadClass(String name, boolean resolve) 
            throws ClassNotFoundException { 
        Class cls = null; 
        cls = findLoadedClass(name);
        if(!this.dynaclazns.contains(name) && cls == null) 
            cls = getSystemClassLoader().loadClass(name);
        if (cls == null) 
            throw new ClassNotFoundException(name); 
        if (resolve) 
            resolveClass(cls); 
        return cls; 
    } 
 
}